#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFileDialog>
#include <QMessageBox>
#include <QTextStream>
#include <QSqlQuery>
#include <QDebug>
#include <QSqlError>
#include <QSqlResult>
#include <PGNGameCollection.h>
#include <PGNGame.h>
#include <fstream>

QString dbHost = "localhost";
QString dbName = "white_knight";
QString dbUser = "root";
QString dbPassword = "azazello";

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    dBHandler = QSqlDatabase::addDatabase("QSQLITE");
    dBHandler.setHostName(dbHost);
    dBHandler.setDatabaseName(dbName);
    dBHandler.setUserName(dbUser);
    dBHandler.setPassword(dbPassword);
         bool ok = dBHandler.open();
         if(ok)
             qDebug("connected!");

    ui->setupUi(this);
    ui->progressBar->hide();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_selectBttn_clicked()
{
    ui->addingList->clear();
    filesPaths = QFileDialog::getOpenFileNames(this, "Select PGN files", QApplication::applicationDirPath(), "Portable Game Notation (*.pgn)");
    foreach(QString filePath, filesPaths)
    {
        QListWidgetItem *item = new QListWidgetItem(ui->addingList);
        QFileInfo fI(filePath);
        item->setText(fI.fileName());
        item->setData(Qt::UserRole, filePath);
        this->ui->addingList->addItem(item);
    }
    ui->statusBar->setStatusTip(QString("Files for adding: ").append(QString::number(ui->addingList->count())));
}

void MainWindow::on_addBttn_clicked()
{
    ui->addBttn->setEnabled(false);
    int gamesAdded = 0;
    ui->progressBar->setMaximum(ui->addingList->count());
    m_succesefulyAdded = 0;
    m_failedAdd = 0;
    for(int i=0; i<ui->addingList->count(); i++)
    {
        QListWidgetItem *item = ui->addingList->item(i);
        gamesAdded += addFile(item->data(Qt::UserRole).toString());
        ui->progressBar->setValue(ui->progressBar->value()+1);
        ui->succesefulyaddedLabel->setText(
                QString("Successeful added: %1").arg(m_succesefulyAdded));
        ui->failedLabel->setText(
                QString("Failed: %1").arg(m_failedAdd)
                );
    }
    ui->statusBar->setStatusTip(QString::number(gamesAdded));
    ui->addBttn->setEnabled(true);
}

int MainWindow::addFile(QString path)
{
    if(path.isEmpty())
    {
        return 0;
    }
    std::ifstream file;
    file.open(path.toStdString().c_str());
    pgn::GameCollection coll;
    file>>coll;
    int i = 0;
    for(pgn::GameCollection::iterator it = coll.begin();
        it != coll.end();
        it++)
    {
        const pgn::Game  tmpGame = (*it);
        QString wId = findPlayer(tmpGame.white().c_str());
        QString bId = findPlayer(tmpGame.black().c_str());

        QString gMoves;
        int mvNum = 1;
        gMoves.append(tmpGame.moves().toStdString().c_str());
        QString gSite;
        if(tmpGame.tags().find("Site"))
            gSite = tmpGame.tags()["Site"].value().c_str();

        QString gEvent;
        if(tmpGame.tags().find("Event"))
            gEvent = tmpGame.tags()["Event"].value().c_str();
        if((!wId.isEmpty()) && (!bId.isEmpty()))
        {
            if(dBHandler.exec(
                    QString("INSERT INTO `white_knight`.`games` (`ID`, `white_player`, `black_player`, `moves`, `result`, `site`, `event`, `date`) VALUES(NULL, %1, %2, '%3', %4, '%5', '%6', '0000-00-00');")
                    .arg(wId,
                         bId,
                         gMoves,
                         convertResult(tmpGame.result()),
                         gSite,
                         gEvent)).isValid())
            {
                m_succesefulyAdded++;
                qDebug()<<"Added game: "<<++i;
            }
            else
            {
                qDebug()<<QString("INSERT INTO `white_knight`.`games` (`ID`, `white_player`, `black_player`, `moves`, `result`, `site`, `event`, `date`) VALUES(NULL, %1, %2, '%3', %4, '%5', '%6', '0000-00-00');")
                        .arg(wId,
                             bId,
                             gMoves,
                             gSite,
                             convertResult(tmpGame.result()),
                             gEvent);
                qDebug()<<dBHandler.lastError().text();
                m_failedAdd++;
            }
        }
    }
    return coll.size();
}

QString MainWindow::convertResult(pgn::GameResult res)
{
    if(res.isWhiteWin())
        return "1";
    if(res.isBlackWin())
        return "2";
    if(res.isDrawn())
        return "3";
    return "*";
}

QString MainWindow::findPlayer(QString name)
{
    QSqlQuery q(
            QString("SELECT `ID` FROM `white_knight`.`players` WHERE `name` = '%1'").arg(name)
            ,dBHandler);
    q.first();
    if(q.size() == 0)
        return addPlayer(name);
    if(q.size() == 1)
        return q.value(0).toString();
    return "";
}

QString MainWindow::addPlayer(QString name)
{
    QSqlQuery q(dBHandler);
    q.prepare("INSERT INTO `white_knight`.`players` (`ID` ,`name` ,`photo_url` ) VALUES(NULL, :pName, '');");
    q.bindValue(":pName", name);
    if(q.exec())
        return findPlayer(name);
    else
        return "-1";
}
